#include<iostream>
using namespace std;


#define NUM_COLORS 10
#define COLOR_STEP (255/NUM_COLORS)

double NewspaperSegmentation::computeEnergy(int x, int y, int neighborhood){
	int coocurrence[NUM_COLORS][NUM_COLORS];
	for( int i = 0; i < NUM_COLORS; ++i )
		for( int j = 0; j < NUM_COLORS; ++j )
			coocurrence[i][j] = 0;
	
	//int offset_x[] = { 1, 1, 0, -1 };   //ver http://www.mathworks.com/help/toolbox/images/ref/graycomatrix.html
	//int offset_y[] = { 0, -1, -1, -1 };
	
	int inc = neighborhood/2;
	int width = min(x+inc, image_step[1]->width()-1);
	int height = min(y+inc, image_step[1]->height());
		
	int total = 0;

	for(int i = max(0, x-inc); i < width; i++)
	   for(int j = max(0, y-inc); j < height; j++) {
			int pixel = qRed( image_step[1]->pixel( i, j ) ) / COLOR_STEP;
			int neighboor = qRed( image_step[1]->pixel( i+1, j ) ) / COLOR_STEP;
			if (pixel >= NUM_COLORS)
			   pixel = NUM_COLORS-1;
			if (neighboor >= NUM_COLORS)
			   neighboor = NUM_COLORS-1;
			coocurrence[pixel][neighboor] += 1;
			total += 1;
		}

	double energy = 0.0;
	for( int i = 0; i < NUM_COLORS; ++i )
		for( int j = 0; j < NUM_COLORS; ++j ){
		   	double temp = coocurrence[i][j] / (double)total;
			energy += pow(temp,2);
		}
	return energy;
}

void NewspaperSegmentation::computeStep2Image(){
	if( image_step[1] == 0 )
		computeStep1Image();
	if( image_step[2] ){
		setCurrentImage( 2 );
		return;
	}
		
	
	image_step[2] = new QImage( image_step[1]->width(), image_step[1]->height(), QImage::Format_RGB32 );
	
	
	//cálculo energia
	for( int y = 0; y < image_step[1]->height(); ++y ){
		for( int x = 0; x < image_step[1]->width(); ++x ){
			double energy = computeEnergy(x,y, this->energy);
			int px = (int)(255*energy);
			if (px <0)
			   px = 0;
			image_step[2]->setPixel( x, y, QColor(px, px, px).rgb() );
		}
		//if (y%10 == 0)
		  // QMessageBox::about ( this, QString("energy"), QString("%1 %2").arg(y).arg(image_step[1]->height()));
	}
	
	//término da implementação
	setCurrentImage( 2 );
}

